package com.pbs.ui;

import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.ContactsContract;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.pbs.contact.Contact;
import com.pbs.ui.dialog.Dialog;
import com.pbs.ui.dialog.Dialog.Type;
import com.pbs.utils.ContactProvider;
import com.pbs.utils.MyXStream;

public class ImportContactFromSDCardActivity extends Activity {
	private ArrayList<Contact>		items					= new ArrayList<Contact>();
	private ListView				lv;
	private ArrayAdapter<Contact>	aa;
	private int						numberOfContactSelected	= 0;
	ContactProvider					cp;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sdcard_contact_list);
		lv = (ListView) findViewById(R.id.List);
		try {
			cp = new ContactProvider();
			cp.setCr(getContentResolver());
			cp.setCur(getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, "display_name ASC"));
			File root = Environment.getExternalStorageDirectory();
			File gpxfile = new File(root, "export.xml");
			FileReader gpxwriter = new FileReader(gpxfile);
			try {
				items = MyXStream.fromXML(gpxwriter);
			} catch (Exception e) {
				Dialog.show(this, "Error!", e.getMessage(), null, null, null,
						null, Type.ERROR);
			}
			numberOfContactSelected = 0;
			aa = new ArrayAdapter<Contact>(this, R.layout.item_contact_info, items) {
				@Override
				public View getView(int position, View convertView, ViewGroup parent) {
					View v = convertView;
					if (v == null) {
						LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
						v = vi.inflate(R.layout.item_contact_info, null);
					}

					Contact contact = items.get(position);

					if (contact != null) {
						TextView tvTopLeftInfo = (TextView) v.findViewById(R.id.tvTopLeftInfo);
						TextView tvTopRightInfo = (TextView) v.findViewById(R.id.tvTopRightInfo);
						TextView tvBottomRightInfo = (TextView) v.findViewById(R.id.tvBottomRightInfo);
						TextView tvBottomLeftInfo = (TextView) v.findViewById(R.id.tvBottomLeftInfo);
						CheckBox chkSelectContact = (CheckBox) v.findViewById(R.id.chkSelectContact);

						chkSelectContact.setChecked(contact.isChecked());

						HashMap<String, String> info = cp.getContactInfoToShow(contact);

						tvTopLeftInfo.setText(contact.getFirstName(info.get("DisplayName")));
						tvTopRightInfo.setText(contact.getLastName(info.get("DisplayName")));
						tvBottomRightInfo.setText(info.get("BottomRightInfo"));
						tvBottomLeftInfo.setText(info.get("BottomLeftInfo"));
					}
					return v;
				}
			};

			lv.setAdapter(aa);
		} catch (Exception e) {
			Dialog.show(this, "Error!", e.getMessage(), null, null, null,
					null, Type.ERROR);
		}

		for (Contact contact : items) {
			if (contact.isChecked()) {
				numberOfContactSelected++;
			}
		}

		if (numberOfContactSelected == items.size()) {
			((Button) ImportContactFromSDCardActivity.this.findViewById(R.id.cmdSelectAll)).setText(R.string.option_menu_item_UnselectAll);
		} else {
			((Button) ImportContactFromSDCardActivity.this.findViewById(R.id.cmdSelectAll)).setText(R.string.option_menu_item_SelectAll);
		}
		// numberOfContactSelected nhan gia tri 0 khi thoat khoi ham getView
	}

	public void contactCheckButtonClick(View v) {
		items.get(lv.getPositionForView(v)).setChecked(((CheckBox) v).isChecked());
		numberOfContactSelected += ((CheckBox) v).isChecked() ? 1 : -1;
		if (numberOfContactSelected == items.size()) {
			((Button) findViewById(R.id.cmdSelectAll)).setText(R.string.option_menu_item_UnselectAll);
		} else {
			((Button) findViewById(R.id.cmdSelectAll)).setText(R.string.option_menu_item_SelectAll);
		}
	}

	public void SelectAllClick(View v) {
		if (numberOfContactSelected == items.size()) {
			((Button) findViewById(R.id.cmdSelectAll)).setText(R.string.option_menu_item_SelectAll);
			numberOfContactSelected = 0;
		} else {
			((Button) findViewById(R.id.cmdSelectAll)).setText(R.string.option_menu_item_UnselectAll);
			numberOfContactSelected = items.size();
		}
		for (Contact contact : items) {
			contact.setChecked(numberOfContactSelected == items.size());
		}
		aa.notifyDataSetChanged();
	}

	private ProgressDialog showProcessDialog() {
		final ProgressDialog pd = new ProgressDialog(this);
		pd.setMessage("Please wait...");
		pd.show();
		return pd;
	}

	Handler	addContactHandler	= new Handler();

	public void AddContactClick(View v) {
		if (numberOfContactSelected > 0) {
			final ProgressDialog pd = showProcessDialog();
			new Thread(new Runnable() {

				@Override
				public void run() {
					for (int i = 0; i < items.size(); i++) {
						final Contact contact = items.get(i);
						if (contact.isChecked()) {
							if (cp.findContactWithName(contact.getDisplayName()) == 0) {
								addContactHandler.post(new Runnable() {

									@Override
									public void run() {
										pd.setMessage("Saving '" + contact.getDisplayName() + "'");
									}
								});
								cp.writeContact(contact);
								items.remove(i--);
							} else {
								addContactHandler.post(new Runnable() {
									@Override
									public void run() {
										Toast.makeText(ImportContactFromSDCardActivity.this, "Contact '" + contact.getDisplayName() + "' had been existed",
												Toast.LENGTH_LONG);
									}
								});
							}
						}
					}
					addContactHandler.post(new Runnable() {
						@Override
						public void run() {							
							pd.dismiss();
							finish();
						}
					});

				}
			}).start();

		} else {
			Toast.makeText(this, R.string.msg_WhenDontSelectContact,
					Toast.LENGTH_LONG);
		}
	}
}
